// pages/diary-add/diary-add.js
var app = getApp();
var moment = require('../../utils/moment.min.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: "2018-01-01",
    bookId: "", //日记本id
    diaryDate: "", //日记时间
    video: "", //
    pic: "",
    content: "", //日记内容
    images: [],
    imagesurl: '',
    videoo: "",
    src: "", //视频路径
    videodata: "", //视频返回路径
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.createDate();
    console.log("id", options)
    var options = options.bookId;
    this.setData({
      bookId: options,
    })
  },

  //选择图片待上传
  chooseImg: function(e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      responseType: 'arraybuffer',
      success: function(res) {

        // 将现有和新上传的合并
        var images = that.data.images.concat(res.tempFilePaths);
        images = images.length <= 6 ? images : images.slice(0, 6);
        that.setData({
          images: images,
        })
        console.log("--123--", that.data.images)
        that.uploadimages(); // 选择图片后 上传到服务器上
      },
    })
  },

  // 上传图片
  uploadimages: function(e) {
    var that = this;
    wx.showToast({
      icon: "loading",
      title: "正在上传"
    });
    var images = this.data.images;
    var imagesArr = [];
    for (var i = 0; i < images.length; i++) {
      console.log("--图片i--", i, images[i])
      wx.uploadFile({
        url: app.globalData.baseUrl + 'doctor/member/uploadFile',
        formData: {
          bookId: that.data.bookId,
          type: 1,
        },
        filePath: images[i],
        name: 'file',
        method: 'POST',
        header: {
          'sign': app.globalData.sign,
          'token': app.globalData.token,
          "Content-Type": "multipart/form-data"
          // 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值
        },

        success: function(res) {
          console.log('---1---', res)
          var path = JSON.parse(res.data).data[0].fileId;
          imagesArr.push(path);
          console.log('图片数组:', imagesArr)
       
          that.setData({
            'imagesurl': imagesArr,
          }) 
          
        },
        fail:function(){
          console.log(99999);
        }
      })
    };
  },

  //选择上传 视频
  scvideo: function() {
    var that = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function(res) {
        console.log("选择视频", res)
        that.setData({
          videoo: res.tempFilePath,
          size: (res.size / (1024 * 1024)).toFixed(2)
        })
        that.uploadvideo(); //上传视频
      }
    })

  },
  //视频上传
  uploadvideo: function() {
    var video = this.data.videoo;
    var that = this;
    var array = [];
    wx.uploadFile({
      url: app.globalData.baseUrl + 'doctor/member/uploadFile',
      formData: {
        bookId: that.data.bookId,
        type: 2,
      },
      // method: 'POST', //这句话好像可以不用
      filePath: video,
      header: {
        'sign': app.globalData.sign,
        'token': app.globalData.token,
        "Content-Type": "multipart/form-data"
        // 'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      name: 'file', //服务器定义的Key值
      success: function(res) {
        console.log('视频上传成功', res)
        var path = JSON.parse(res.data).data[0].fileId;
        array.push(path);
        console.log('视频数组:', array)
        that.setData({
          videodata: array
        })
        console.log("视频测试1", that.data.videodata)
        // console.log("视频测试2", videodata[0].fileId)
      },
      fail: function() {
        console.log('接口调用失败')
      }
    })
  },

  // 删除图片
  deleteimg: function(e) {
    console.log("666",e);
    var index = e.target.dataset.index;
    var imagesurl = this.data.imagesurl;
    var images = this.data.images;
    imagesurl.splice(index, 1);
    images.splice(index, 1);
    this.setData({
      'imagesurl': imagesurl,
      'images': images,
    });
    console.log(this.data.imagesurl);
  },


  // 保存信息
  save: function(e) {
    var that = this
    //内容
    if (e.target.dataset.name == "content") {
      this.setData({
        content: e.detail.value
      });
      // console.log("内容:", that.data.content)
    }
  },

  // 完成提交
  accomplish: function(e) {
    var that = this
    var content = that.data.content;
    var diaryDate = that.data.time;
    var bookId = that.data.bookId;
    var imagesurl = that.data.imagesurl;
    var video = that.data.videodata;
    console.log("内容", content)
    console.log("id", bookId)
    console.log("图片", imagesurl)
    console.log("视频", video)
    console.log("时间", diaryDate)
    if (content == ""){
      wx.showToast({
        title: '请输入日记内容',
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    if (imagesurl == "") {
      wx.showToast({
        title: '请选择上传图片',
        icon: 'none',
        duration: 1000
      })
      return false;
    }
   
    wx.request({
      url: app.globalData.baseUrl + 'doctor/diary/create', //仅为示例，并非真实的接口地址
      data: {
        bookId: bookId,
        diaryDate: diaryDate,
        pic: imagesurl,
        content: content,
        video: video,
      },
      method: 'POST',
      header: {
        'sign': app.globalData.sign,
        'token': app.globalData.token,
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值
      },
      success(res) {
        console.log("创建日记", res)
        if (res.data.message == "新建日记成功"){
          wx.navigateTo({
            url: '../user-diary-book-add-5/user-diary-book-add-5',
          })
        }else{
          wx.navigateTo({
            url: '../user-diary-list/user-diary-list',
          })
          wx.showModal({
            title: '提示',
            content: '手术已取消或正在售后流程中不可创建日记',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            } 
          })

        }
        

      }
    })


  },

  // 日期选择按钮
  //   bindDateChange: function (e) {
  //     console.log('时间选择器:',e.detail.value);

  // var data = e.detail.value;

  //     var hour = date.getHours()

  //     var minute = date.getMinutes()

  //     var second = date.getSeconds()

  // console.log('aaa:',hour,minute,second);

  //     this.setData({
  //       time: e.detail.value
  //     })
  //   },

  // 生成时间
  createDate: function(e) {
    var time = moment().format('YYYY-MM-DD HH:mm:ss');
    console.log('时间:', time);
    this.setData({
      time: time
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})